using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using OpenWaves.Reflection;
using System.Linq;

namespace OpenWaves
{
    public static class ServiceLocator
    {
        private static IResolver currentResolver = Resolver.Null;

        [ThreadStatic]
        private static IResolver currentScopedResolver;

        public static void SetResolver(IResolver resolver)
        {
            Contract.Requires<ArgumentNullException>(resolver != null);

            currentResolver = resolver;
        }

        public static IDisposable SetScopedResolver(IResolver resolver)
        {
            Contract.Requires<ArgumentNullException>(resolver != null);
            
            var previousResolver = currentScopedResolver;
            var scopedResolver = new ScopedResolver(resolver, previousResolver);

            currentScopedResolver = scopedResolver;

            return scopedResolver;
        }

        public static T Resolve<T>() where T : class
        {
            Contract.Ensures(Contract.Result<T>() != null);
            
            T service;
            var resolved = TryResolve(out service);

            Contract.Assert(resolved, String.Format(CultureInfo.InvariantCulture, "Unable to resolve service of type {0} using current resolver.", typeof(T)));
            Contract.Assert(service != null);

            return service;
        }

        public static T ResolveOptional<T>() where T : class
        {
            T service;
            return TryResolve(out service) ? service : null;
        }

        public static bool TryResolve<T>(out T service) where T : class
        {
            if (currentScopedResolver != null)
            {
                if (currentScopedResolver.TryResolve(out service))
                    return true;
            }

            if (currentResolver.TryResolve(out service))
                return true;

            //
            // Failed to resolve implementation, try the default implementation before giving up.
            //
            if (DefaultServiceImplementation<T>.Instance != null)
            {
                service = DefaultServiceImplementation<T>.Instance;
                return true;
            }

            service = null;
            return false;
        }

        private static class DefaultServiceImplementation<T> 
        {
            public static readonly T Instance = CreateInstance();

            private static T CreateInstance()
            {
                var defaultImplementationAttribute = typeof(T).GetCustomAttributes<DefaultImplementationAttribute>().SingleOrDefault();
                if (defaultImplementationAttribute == null)
                    return default(T);

                return (T)Activator.CreateInstance(defaultImplementationAttribute.ImplementationType);
            }
        }

        private class ScopedResolver : IDisposable, IResolver
        {
            private readonly IResolver resolver;
            private readonly IResolver previousResolver;

            public ScopedResolver(IResolver resolver, IResolver previousResolver)
            {
                Contract.Requires<ArgumentNullException>(resolver != null);

                this.resolver = resolver;
                this.previousResolver = previousResolver;
            }

            public void Dispose()
            {
                try
                {
                    if (this.resolver is IDisposable)
                    {
                        ((IDisposable)this.resolver).Dispose();
                    }
                }
                finally
                {
                    currentScopedResolver = this.previousResolver;
                }
            }

            public bool TryResolve<T>(out T service) where T : class
            {
                if (this.resolver.TryResolve(out service))
                    return true;

                if (this.previousResolver != null)
                    return this.previousResolver.TryResolve(out service);

                return false;
            }
        }
    }
}